package netclient;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
import java.util.Scanner;

/*
 * For now, messageHandler's job is to take any message reveived from netIO
 and print it to the console.
 */

public class MessageHandler extends Thread {
	Socket sock;
	Scanner netIn;
	
	ReturnObject out;
	
	public MessageHandler(Socket sock, Scanner netIn, ReturnObject out) {
		this.out = out;
		
		this.sock = sock;
		this.netIn = netIn;
		System.out.println("Constructed MsgHand");
	}

	public void run() {
		if (sock == null) {
			System.err.println("NO SOCKET!");
		}
		
		String fromServer = "";
		while (sock != null) {
			String received = "";
			while (netIn.hasNextLine()) {
				received = netIn.nextLine();
				System.out.println("MessageHandler recieved one line: " + received);
				fromServer += received;
				//resultStream = new ByteArrayInputStream(received.getBytes());
				if (received.charAt(received.length()-1) == ';') {
					break;
				}
			}
			System.out.println("MessageHandler thread shutting down.");
			
			if (out != null)
				out.setData(fromServer);
				//System.out.println("MessageHandler is trying to say:" + out.getData() );
		}
	}

	public void finalize() {
		
		try {
			netIn.close();
			sock.close();
		} catch(Exception e) {}
		
		sock = null;
	}
}